<template>
  <div class="flex-box">
    <div class="flex-inner login">
      <h2>Welcome~</h2>
      <vanForm @submit="onSubmit">
        <vanField v-model="username" name="username" label="用户名" placeholder="用户名" :rules="[{ required: true, message: '请填写用户名' }]" />
        <vanField v-model="password" type="password" name="password" label="密码" placeholder="密码" :rules="[{ required: true, message: '请填写密码' }]" />
        <div style="margin: 1rem;">
          <vanButton round block type="info" native-type="submit">
            登录
          </vanButton>
        </div>
      </vanForm>
    </div>
  </div>
</template>

<script>
  import {
    Form,
    Field,
    Button,
    Notify
  } from 'vant';
  import axios from "axios";
  export default {
    name: 'Login',
    components: {
      vanForm: Form,
      vanField: Field,
      vanButton: Button,
    },
    data() {
      return {
        username: '',
        password: '',
        apisUrl: `http://${window.location.hostname}:3000/apis`
      }
    },
    methods: {
      onSubmit() {
        let apisUrl = this.apisUrl;
        if (!this.username || !this.password) {
          Notify("用户名或密码为空！")
          return;
        }
        let body = {
          username: this.username,
          password: this.password
        }
        
        this.$loading(true, "hand");
        axios.post(`${apisUrl}/login`, body).then(res => {
          if (res.status == 200) {
            this.$loading(false, "hand");
            window.sessionStorage.setItem("loginToken", apisUrl);
            Notify({type: 'success', message: res.data.msg});
            this.goto(['Home']);
          }
        }).catch(err => {
          window.sessionStorage.clear();
          this.$loading(false, "hand");
          Notify({type: 'danger', message: err.response.data.msg});
        })
      },
    },
  }
</script>
